package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.admin.mapper.DiscountMapper;
import com.shop.admin.mapper.DiscountPreMapper;
import com.shop.admin.model.po.DiscountPre;
import com.shop.admin.model.po.dto.DiscountPreDto;
import com.shop.admin.service.DiscountService;
import com.shop.ex.ShoppingException;
import com.shop.mapper.MessageMapper;
import com.shop.po.Discount;
import com.shop.po.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-02-26
 */
@Service
@Slf4j
public class DiscountServiceImpl extends ServiceImpl<DiscountMapper, Discount> implements DiscountService {

    @Autowired
    private DiscountMapper discountMapper;

    @Autowired
    private DiscountPreMapper discountPreMapper;

    @Autowired
    private MessageMapper messageMapper;

    //用于发布时间转换为字符串
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public boolean changDiscountCount(Long discountId, Long count) {
        int i=discountMapper.changDiscountCount(discountId,count);
        if (i==0) return false;
        return true;
    }

    //发送到待发布表中
    @Override
    @Transactional
    public void addDiscount(DiscountPreDto discountPreDto) {
        //获取信息。。
        DiscountPre discountPre = new DiscountPre();
        BeanUtils.copyProperties(discountPreDto,discountPre);
        int i = discountPreMapper.insert(discountPre);
        if (i == 0) {
            ShoppingException.ThrowShoppingException("添加优惠券失败");
        }
        //这里把信息存储到消息表中
        Message message = new Message();
        message.setMessageType("discountPublish");//注意这个type名称
        message.setBusinessKey1(discountPre.getId().toString());
        String publishTime = this.dateFormat.format(discountPre.getPublishTime());
        message.setBusinessKey2(publishTime);
        int j = messageMapper.insert(message);
        if (j == 0) {
            ShoppingException.ThrowShoppingException("消息插入失败，请重新添加优惠券");
        }


    }

    @Override
    public List<Discount> getDiscountBatch(List<Long> discountIds) {
        List<Discount> discounts = discountMapper.selectBatchIds(discountIds);
        return discounts;
    }

    @Override
    public Discount getDiscountById(Long discountId) {
        Discount discount = discountMapper.selectById(discountId);
        if (discount == null) {
            log.debug("该优惠券不存在");
//            ShoppingException.ThrowShoppingException("该优惠券不存在");
        }
        return discount;
    }
}
